import axios from 'axios'
import { Message } from 'element-ui'
import store from '@/store'
import router from '@/router'
// import { getToken } from '@/utils/auth'

// create an axios instance
const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_API,
  timeout: 5000 // request timeout
})

// 请求拦截器
service.interceptors.request.use(
  async config => {
    console.log('所有正常的响应会经过这里')
    if (store.getters.token) {
      // 如果token存在的话
      config.headers['Authorization'] = 'Bearer ' + store.getters.token
    }
    return config
  },
  error => {
    return Promise.reject(error)
  }
)

// 响应拦截器
service.interceptors.response.use(

  response => {
    console.log('所有正常的响应到达浏览器之前一定会经过这里')
    if (response.data instanceof Blob) return response.data // 返回了Blob对象
    const { data, success, message } = response.data

    // if the custom code is not 20000, it is judged as an error.
    if (success) {
      return data
    } else {
      Message({ type: 'error', message })
      return Promise.reject(new Error(message))
    }
  },
  error => {
    if (error.response.status === 401) {
      Message({ type: 'error', message: 'token失效了' })
      store.dispatch('user/logout')
      router.push('/login')
    } else {
      Message({ type: 'error', message: error.message })
    }
    console.log('所有错误都会走这儿')

    return Promise.reject(error)
  }
)

export default service
